package com.snowfeel.sfmall.order.config;

import com.snowfeel.sfmall.security.constants.SecurityConstants;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author guomenghuai
 * @date 2024/9/8
 * @Description
 */
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;

            // 当主线程的请求执行完毕后，Servlet容器会被销毁当前的Servlet，因此在这里需要做判空
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();

                // 获取token 并传递 token
                String token = request.getHeader(SecurityConstants.AUTHORIZATION);
                if (StringUtils.hasText(token)) {
                    template.header(SecurityConstants.AUTHORIZATION, token);
                }
            }
        };
    }
}
